// server/http.js
require('asar-node').register();
const fs = require('fs');
const http = require('http')
const path = require('path')

const config = {
    root: 'D:\\codes\\node\\electron_web_manager\\pack\\resources\\cawater.asar',
    host: '127.0.0.1',
    port: '8877'
}

const returnAs404 = (response,filePath) => {
    response.statusCode = 404
    response.setHeader('content-type', 'text/plain')
    response.end(`${filePath} is not a file`)
};
const requestFile = function (request, response, filePath,last) {
    console.log(filePath);
    if (fs.existsSync(filePath)) {
        let stats = fs.lstatSync(filePath);
        if (stats.isFile()) {
            if (filePath.includes('.html') || filePath.includes('.htm')) {
                response.setHeader('content-type', 'text/html');
            } else if (filePath.includes('.js')) {
                response.setHeader("content-type", "application/javascript");
            } else if (filePath.includes('.pdf')) {
                response.setHeader("content-type", "application/pdf");
            } else if (filePath.includes('.css')) {
                response.setHeader("content-type", "text/css");
            } else {
                response.setHeader('content-type', 'text/plain');
            }
            response.statusCode = 200;
            fs.createReadStream(filePath).pipe(response);
        }
        else if (stats.isDirectory()) {
            fs.readdir(filePath, (err, files) => {
                response.statusCode = 200
                response.setHeader('content-type', 'text/plain')
                response.end(files.join(','))
            })
        }
    } else {
        if (last) {
            return returnAs404(response,filePath);
        } else if (filePath.indexOf('?') !== -1) {
            requestFile(request,response,filePath.split('?')[0]);
        } else if (filePath.endsWith('/') || filePath.endsWith('\\')) {
            requestFile(request,response,filePath + "index.html");
        } else if (filePath) {
            if (fs.existsSync(path.join(filePath,'index.html'))) {
                requestFile(request,response,path.join(filePath,'index.html'),true);
            } else if (fs.existsSync(filePath + '.html')) {
                requestFile(request,response,filePath + ".html",true);
            } else {
                return returnAs404(response,filePath);
            }
        } else {
            return returnAs404(response,filePath);
        }
    }
};



module.exports = function () {
    let server = null;

    return {
        start(root,port) {
            config.root = root;
            if (server) {
                return server;
            } else {
                config.port = port;
            }
            server = http.createServer((request, response) => {
                let filePath = path.join(config.root, request.url);
                requestFile(request, response, filePath);
            });

            server.listen(config.port, config.host, () => {
                const addr = `http://${config.host}:${config.port}`;
                console.info(`server started at ${addr}`);
            });
            return server;
        }
    };
}
